The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expressionx+y.

The functions fall into categories that perform

  • object comparisons
  • logical operations
  • mathematical operations
  • sequence operations
  • abstract type tests

Few examples of operators: </pre> operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) </pre>

The operator module also defines tools for generalized attribute and item lookups. These are useful for making fast field extractors as arguments for map(), sorted(), itertools.groupby(), or other functions that expect a function argument.


operator.attrgetter(attr)
operator.attrgetter(*attrs)
Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots. For example:


In [ ]:
import operator

class foo():
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

foo_object = foo('foo', 'bar')
first_name_getter = operator.attrgetter('first_name')
# first_name_getter(foo_object) returns 
# foo_object.first_name
print first_name_getter(foo_object)
# name_getter(foo_object) returns 
# (foo_object.first_name, foo_object.last_name)
name_getter = operator.attrgetter('first_name', 'last_name')
print name_getter(foo_object)

operator.itemgetter(item) operator.itemgetter(*items) Return a callable object that fetches item from its operand using the operand’s \_\_getitem\_\_() method. If multiple items are specified, returns a tuple of lookup values. For example:


In [ ]:
foo = [1, 2, 3, 4, 5]
elem_getter = operator.itemgetter(2)
# elem_getter(foo) would return
# foo[2]
print elem_getter(foo)
# elem_getter(foo) would return
# (foo[2], foo[3])
elem_getter = operator.itemgetter(2, 3)
print elem_getter(foo)

foo_dict = {'first_name': 'foo', 'last_name':'bar'}
elem_getter = operator.itemgetter('first_name', 'last_name')
print elem_getter(foo_dict)

operator.methodcaller(name[, args...])
Return a callable object that calls the method name on its operand. If additional arguments and/or keyword arguments are given, they will be given to the method as well. For example:


In [ ]:
class foo():
    def foo_function(self, first_name='foo', last_name='bar'):
        print first_name, last_name

foo_object = foo()
method_caller = operator.methodcaller('foo_function')
# method_caller(foo_object) would return 
# foo_object.name()
method_caller(foo_object)
# method_caller(foo_object) would return
# foo_object.name(first_name='first', last_name='last')
method_caller = operator.methodcaller('foo_function', first_name='first', last_name='last')
method_caller(foo_object)

Sorting using operator.attrgetter and operator.itemgetter


In [ ]:
class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age
    def __repr__(self):
        return repr((self.name, self.grade, self.age))

student_objects = [
        Student('john', 'A', 15),
        Student('jane', 'B', 12),
        Student('dave', 'B', 10),
        ]
print sorted(student_objects, key=lambda student: student.age)
print sorted(student_objects, key=operator.attrgetter('age'))

In Python, sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.


In [ ]:
data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
print sorted(data, key=operator.itemgetter(0))
# Notice how the two records for 'blue' retain their 
# original order so that ('blue', 1) 
# is guaranteed to precede ('blue', 2)